package genesis.familytree.server.common.captcha;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

@Configuration
@EnableConfigurationProperties(KaptchaProperties.class)
public class KaptchaAutoConfiguration {

    @Bean
    public Producer producer(Config config) {
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }

    @Bean
    public Config config(KaptchaProperties kaptchaProperties) {
        Properties properties = new Properties();

        properties.setProperty(Constants.KAPTCHA_BORDER, kaptchaProperties.getBorder() ? "yes" : "no");
        properties.setProperty(Constants.KAPTCHA_BORDER_COLOR, kaptchaProperties.getBorderColor());
        properties.setProperty(Constants.KAPTCHA_IMAGE_WIDTH, kaptchaProperties.getImageWidth() + "");
        properties.setProperty(Constants.KAPTCHA_IMAGE_HEIGHT, kaptchaProperties.getImageHeight() + "");

        properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_COLOR, kaptchaProperties.getTextProducerFontColor());
        properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_SIZE, kaptchaProperties.getTextProducerFontSize() + "");
        properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, kaptchaProperties.getTextProducerCharLength() + "");
        properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_STRING, kaptchaProperties.getTextProducerCharString() + "");
        properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_NAMES, kaptchaProperties.getTextProducerFontNames() + "");
        properties.setProperty(Constants.KAPTCHA_OBSCURIFICATOR_IMPL, kaptchaProperties.getObscurificatorImpl().getName());
        properties.setProperty(Constants.KAPTCHA_NOISE_IMPL, kaptchaProperties.getNoiseImpl().getName());
        properties.setProperty(Constants.KAPTCHA_WORDRENDERER_IMPL, kaptchaProperties.getWordRendererImpl().getName());

        return new Config(properties);
    }
}
